﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YYNY.Tools;
using YYNY.Tools.Dao;
using System.IO;
using Newtonsoft.Json.Linq;

namespace YYNY.Controllers
{
    public class ProjectController : Controller
    {
        BaseDao dao = new BaseDao();
        // GET: Project
        public ActionResult InfoAdd()
        {
            ViewBag.ProjectId = "";
            ViewBag.ProJectCode = "";
            ViewBag.Name = "";
            ViewBag.Content = "";
            ViewBag.Adress = "";
            ViewBag.BidTime = "";
            ViewBag.state = "";
            ViewBag.type = "";
            ViewBag.BidBody = "";
            ViewBag.BidAmount = "";
            ViewBag.ConAmount = "";
            ViewBag.PayStyle = "";

            return View("InfoEditView");
        }

        public ActionResult InfoEdit()
        {
            string ProjectId = Request.QueryString["ProjectId"] == null ? null : Request.QueryString["ProjectId"].ToString();
            string sql = "select * from t_d_ProjectInfo where ProjectId=" + ProjectId;
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            try
            {
                list = dao.GetList(sql, new string[] { "ProjectId", "ProjectCode", "Name", "Content", "Adress", "ContrTime", "type", "ConAmount", "PayStyle" });

                ViewBag.ProjectId = ProjectId;
                ViewBag.ProJectCode = list[0]["ProjectCode"].ToString();
                ViewBag.Name = list[0]["Name"].ToString();
                ViewBag.Content = list[0]["Content"].ToString();
                ViewBag.Adress = list[0]["Adress"].ToString();
                if (list[0]["ContrTime"].ToString() != "")
                {
                    ViewBag.ContrTime = DateTime.Parse(list[0]["ContrTime"].ToString()).ToString("yyyy-MM-dd");
                }
                else
                {
                    ViewBag.ContrTime = "";
                }
                
                ViewBag.type = list[0]["type"].ToString();
                ViewBag.ConAmount = list[0]["ConAmount"].ToString();
                ViewBag.PayStyle = list[0]["PayStyle"].ToString();

                return View("InfoEditView");

            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /ProjectController/InfoEdit:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }
            

        }


        public ActionResult InfoView()
        {
            return View("InfoView");
        }

        public ActionResult BidInfoView()
        {
            return View();
        }

        public ActionResult BidInfoAddView()
        {
            return View("BidEditView");
        }

        public ActionResult BidInfoAdd()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);    
                }
                map.Add("IsDelete", "0");
                //string InventoryId = map["InventoryId"].ToString();
                //map.Remove("InventoryId");

                dao.save("t_d_ProjectInfo", map);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult BidInfoEdit()
        {
            string ProjectId = Request.QueryString["ProjectId"] == null ? null : Request.QueryString["ProjectId"].ToString();
            string sql = "select * from t_d_ProjectInfo where ProjectId=" + ProjectId;
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            try
            {
                list = dao.GetList(sql, new string[] { "ProjectId", "ProjectCode", "Name", "BidTime", "BidState", "type", "BidAmount", "WinnAmount", "WinnName" });

                ViewBag.ProjectId = ProjectId;
                ViewBag.ProJectCode = list[0]["ProjectCode"].ToString();
                ViewBag.Name = list[0]["Name"].ToString();
                ViewBag.BidTime = DateTime.Parse(list[0]["BidTime"].ToString()).ToString("yyyy-MM-dd");
                ViewBag.BidState = list[0]["BidState"].ToString();
                ViewBag.type = list[0]["type"].ToString();
                ViewBag.BidAmount = list[0]["BidAmount"].ToString();
                ViewBag.WinnAmount = list[0]["WinnAmount"].ToString();
                ViewBag.WinnName = list[0]["WinnName"].ToString();


                return View("BidEditView");


            }
            catch (Exception ex)
            {

                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /ProjectController/BidInfoEdit:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }
        }

        public ActionResult BidInfoUpdate()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                string ProjectId = map["ProjectId"].ToString();


                map.Remove("ProjectId");
                //string InventoryId = map["InventoryId"].ToString();
                //map.Remove("InventoryId");

                dao.update("t_d_ProjectInfo", map, "ProjectId="+ ProjectId);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult BidInfoDel()
        {
            string ProjectId = Request.Form["ProjectId"] == null ? null : Request.Form["ProjectId"].ToString().Replace(" ", "");
            string sql = "update t_d_ProjectInfo set IsDelete=1 where ProjectId=" + ProjectId;

            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult InfobriefView()
        {
            string ProjectId = Request.QueryString["ProjectId"] == null ? null : Request.QueryString["ProjectId"].ToString();
            string sql = "select * from t_d_ProjectInfo where ProjectId=" + ProjectId;
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
            list = dao.GetList(sql, new string[] { "ProjectId", "ProjectCode", "Name", "Content", "Adress", "ContrTime", "type", "ConAmount", "PayStyle" });

            try
            {
                ViewBag.ProJectCode = list[0]["ProjectCode"].ToString();
                ViewBag.Name = list[0]["Name"].ToString();
                ViewBag.Content = list[0]["Content"].ToString();
                ViewBag.Adress = list[0]["Adress"].ToString();
                ViewBag.ContrTime = list[0]["ContrTime"].ToString();
                ViewBag.type = list[0]["type"].ToString();
                ViewBag.ConAmount = list[0]["ConAmount"].ToString();
                ViewBag.PayStyle = list[0]["PayStyle"].ToString();


                return View("InfobriefView");
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /ProjectController/InfoTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }
            



            
        }

        /// <summary>
        /// 该表格函数用在投标和中标内
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InfoTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();


            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,ProjectId,ProjectCode,Name,Content,Adress" +
                        " ,LogUserId,CONVERT(varchar(100),BidTime,23) as BidTime,state,type,BidBody,ConAmount,BidAmount,BidState,WinnAmount,WinnName,CONVERT(varchar(100),ContrTime,23) as ContrTime" +
                        " FROM t_d_ProjectInfo " +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "ProjectId", "ProjectCode", "Name", "Content", "Adress", "LogUserId", "BidTime", "state", "type", "BidBody", "ConAmount", "BidAmount", "BidState", "WinnAmount", "WinnName", "ContrTime" });
                SqlNum = "select count(ProjectId) as TotalNum FROM t_d_ProjectInfo where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /ProjectController/InfoTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }

        }

        [HttpPost]
        public ActionResult InfoSave()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            string ProJectCode = obj["ProJectCode"] == null ? null : obj["ProJectCode"].ToString().Replace(" ", "");
            string Name = obj["Name"] == null ? null : obj["Name"].ToString().Replace(" ", "");
            string Content = obj["Content"] == null ? null : obj["Content"].ToString().Replace(" ", "");
            string Adress = obj["Adress"] == null ? null : obj["Adress"].ToString().Replace(" ", "");
            string BidTime = obj["BidTime"] == null ? null : obj["BidTime"].ToString().Replace(" ", "");
            string state = obj["state"] == null ? null : obj["state"].ToString().Replace(" ", "");
            string type = obj["type"] == null ? null : obj["type"].ToString().Replace(" ", "");
            string BidBody = obj["BidBody"] == null ? null : obj["BidBody"].ToString().Replace(" ", "");
            string BidAmount = obj["BidAmount"] == null ? null : obj["BidAmount"].ToString().Replace(" ", "");
            string ConAmount = obj["ConAmount"] == null ? null : obj["ConAmount"].ToString().Replace(" ", "");
            string PayStyle = obj["PayStyle"] == null ? null : obj["PayStyle"].ToString().Replace(" ", "");

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>()
                {
                    ["ProJectCode"] = ProJectCode,
                    ["Name"] = Name,
                    ["Content"] = Content,
                    ["Adress"] = Adress,
                    ["BidTime"] = BidTime,
                    ["state"] = state,
                    ["type"] = type,
                    ["BidBody"] = BidBody,
                    ["BidAmount"] = BidAmount,
                    ["ConAmount"] = ConAmount,
                    ["PayStyle"] = PayStyle,
                    ["LogUserId"] = Request.Cookies["UserID"].Value,
                    ["IsDelete"]=0,
                };
                dao.save("t_d_ProjectInfo", map);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult InfoUpdata()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();


            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                if (map["ContrTime"].ToString() == "")
                {
                    map["ContrTime"] = null;
                }
                if (map["ConAmount"].ToString() == "")
                {
                    map["ConAmount"] = null;
                }
                string ProjectId = map["ProjectId"].ToString();


                map.Remove("ProjectId");
                //string InventoryId = map["InventoryId"].ToString();
                //map.Remove("InventoryId");

                dao.update("t_d_ProjectInfo", map, "ProjectId=" + ProjectId);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        /// <summary>
        /// 所有文件
        /// </summary>
        /// <returns></returns>
        public ActionResult FileView()
        {
            string ProjectId = Request.QueryString["ProjectId"] == null ? null : Request.QueryString["ProjectId"].ToString();
            if (ProjectId == null || ProjectId=="")
            {
                ViewBag.ProjectId = "";
            }
            else
            {
                ViewBag.ProjectId = ProjectId;
            }
            string sql = "select ProjectId,Name,ProjectCode,Type from t_d_ProjectInfo where IsDelete<>1";
            var ProjectList = dao.GetList(sql, new string[] { "ProjectId", "Name", "ProjectCode", "Type" });
            ViewBag.ProjectList = ProjectList;
            return View();
        }

        public ActionResult FileTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();


            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,FileId,ProjectId,Name,Path" +
                        "" +
                        " FROM t_d_File" +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "FileId", "ProjectId", "Name", "Path" });
                SqlNum = "select count(FileId) as TotalNum  FROM t_d_File  where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /PurchaseController/FileTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }

        }

        public ActionResult Upload()
        {


            string tpye = Request.Files[0].ContentType;
            string UpName = Request.Files[0].FileName;
            //获取后缀名
            string exName = UpName.Substring(UpName.LastIndexOf(".") + 1, (UpName.Length - UpName.LastIndexOf(".") - 1));
            string fileName = "File" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + exName;
            if (Directory.Exists(Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMdd"))) == false)//如果不存在就创建file文件夹
            {
                Directory.CreateDirectory(Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMdd")));
            }
            string filePhysicalPath = Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName);
            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                if (Request.Form["ProjectId"] == "")
                {
                    result.Add("result", "没有选择主项目");
                    return Json(result);
                }

                Request.Files[0].SaveAs(filePhysicalPath);

                Dictionary<string, object> map = new Dictionary<string, object>()
                {
                    ["ProjectId"] = Request.Form["ProjectId"],
                    ["Name"] = UpName,
                    ["Path"] = "/upload/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName,
                    ["IsDelete"] = 0
                };
                dao.save("t_d_File", map);

                result.Add("result", "OK");
                return Json(result);
                //upImg.SaveAs(filePhysicalPath);
                //pic = "/upload/" + fileName;
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }

        }

        public ActionResult Download()
        {
            string Path = Request.Form["Path"].ToString();
            string Name = Request.Form["Name"].ToString();
            string filePath = Server.MapPath("~" + Path);//路径
            return File(filePath, "application/unknow", Name); //Name是客户端保存的名字
        }

        public ActionResult FilelDel()
        {
            string FileId = Request.Form["FileId"] == null ? null : Request.Form["FileId"].ToString().Replace(" ", "");
            string sql = "update t_d_File set IsDelete=1 where FileId=" + FileId;

            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult QueryProjectInfo()
        {
            string ProjectId = Request.Form["ProjectId"] == null ? null : Request.Form["ProjectId"].ToString().Replace(" ", "");
            string sql = "select * from t_d_ProjectInfo where ProjectId=" + ProjectId;

            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                var list = dao.GetList(sql, new string[] { "Name", "ProjectCode", "type" });
                if (list.Count > 0)
                {
                    result = list[0];
                    result.Add("result", "OK");
                    return Json(result);
                }
                else
                {
                    result.Add("result", "获取项目信息错误");
                    return Json(result);
                }


            }
            catch (Exception e)
            {

                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
            

       
        }

    }
}